package com.thread.demo;

/**
 * package org.apache.ambari.server
 * description:
 *
 * @author tree
 * @date 2019-05-16 20:42
 */
public class Test {

    public static void main(String[] args) {
        Printer printer = new Printer();
        PrintA printA = new PrintA(printer);
        PrintB printB = new PrintB(printer);

        Thread threadA = new Thread(printA,"A");
        Thread threadB = new Thread(printB, "B");

        threadA.start();
        threadB.start();
    }
}

class Printer{
    //最大打印次数
    private final int MAX_COUNT = 7;
    //false表示该打印机未打印A,true表示该打印机正在打印A
    private boolean printingA = false;
    private int count = 0;

    public synchronized void printA(){
        System.out.print(count++);
        printingA = true;
        System.out.print("A-");
        notifyAll();
    }
    public synchronized void printB(){
        System.out.print(count++);
        printingA = false;
        System.out.print("B-");
        notifyAll();
    }
    public synchronized void aWaiting() throws InterruptedException{
        while(printingA == true){
            wait();
        }
    }
    public synchronized void bWaiting() throws InterruptedException{
        while(printingA == false){
            wait();
        }
    }

    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
    public int getMAX_COUNT() {
        return MAX_COUNT;
    }
}

class PrintA implements Runnable{

    private Printer printer;

    public PrintA(Printer printer) {
        super();
        this.printer = printer;
    }

    @Override
    public void run() {
        while(printer.getCount() < printer.getMAX_COUNT()){

            printer.printA();

            try {
                printer.aWaiting();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

}

class PrintB implements Runnable{

    private Printer printer;

    public PrintB(Printer printer) {
        super();
        this.printer = printer;
    }

    @Override
    public void run() {
        while(printer.getCount() < printer.getMAX_COUNT()){

            try {
                printer.bWaiting();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            printer.printB();

        }
    }

}